import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

typedef TreeSelectMultipleDataFun = Function(
    List mapList, List idList, List valueList, String dataJson);

class TreeSelectMultipleView extends StatefulWidget {
  // 子集Key
  final String childrenKey;
  // idKey
  final String idKey;
  // valueKey
  final String valueKey;
  // 数据
  final List dataList;
  // 已选数据
  final String dataJson;
  // 初始化选择数据
  final String initSelect;
  // 是否默认展开;
  final bool expand;
  // 取消回调
  final Function? onCancel;
  // 确认回调
  final TreeSelectMultipleDataFun? onConfirm;

  const TreeSelectMultipleView({
    required this.childrenKey,
    required this.idKey,
    required this.valueKey,
    required this.dataList,
    required this.dataJson,
    this.initSelect = '',
    this.expand = false,
    this.onCancel,
    this.onConfirm,
    Key? key,
  }) : super(key: key);

  @override
  _TreeSelectMultipleViewState createState() => _TreeSelectMultipleViewState();
}

class _TreeSelectMultipleViewState extends State<TreeSelectMultipleView> {
  TextEditingController controller = TextEditingController();

  List dataList = [];

  List<String> initSelectList = [];

  @override
  void initState() {
    super.initState();
    if (widget.dataJson.isEmpty) {
      if (widget.initSelect.isNotEmpty && widget.initSelect.contains(',')) {
        initSelectList = widget.initSelect.split(',');
      }
      dataList.addAll(jsonDecode(jsonEncode(widget.dataList)));
    } else {
      dataList.addAll(jsonDecode(widget.dataJson));
    }
    setState(() {});
  }

  @override
  void dispose() {
    super.dispose();
  }

  bool searchMake(List dataList, String value) {
    bool parentShow = false;
    for (Map item in dataList) {
      if (item[widget.childrenKey] != null &&
          item[widget.childrenKey].length != 0) {
        item['show'] = searchMake(item[widget.childrenKey] ?? [], value);
        parentShow = parentShow || item['show'];
      } else {
        if (item[widget.valueKey].contains(value)) {
          item['show'] = true;
          parentShow = true;
        } else {
          item['show'] = false;
        }
      }
    }
    return parentShow;
  }

  selectDataMake(
      List dataList, List tempMapList, List tempIdList, List tempNameList) {
    for (Map item in dataList) {
      if (item[widget.childrenKey] != null) {
        selectDataMake(
            item[widget.childrenKey], tempMapList, tempIdList, tempNameList);
      } else {
        if (item['check'] == 2) {
          tempMapList.add(item);
          tempNameList.add(item[widget.valueKey]);
          tempIdList.add(item[widget.idKey]);
        }
      }
      item['show'] = true;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Expanded(child: Container()),
        Container(
          padding: EdgeInsets.all(10.w),
          decoration: BoxDecoration(
            color: Colors.white,
            // 圆角设置
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(18.w),
              topRight: Radius.circular(18.w),
            ),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              InkWell(
                onTap: () {
                  Navigator.pop(context);
                  if (widget.onCancel != null) {
                    widget.onCancel!();
                  }
                },
                child: Container(
                  padding: EdgeInsets.only(left: 10.w),
                  color: Colors.white,
                  child: Text(
                    '取消',
                    style:
                        TextStyle(color: Colors.grey.shade500, fontSize: 14.w),
                  ),
                ),
              ),
              Text(
                '请选择',
                style: TextStyle(color: Colors.black, fontSize: 16.w),
              ),
              InkWell(
                onTap: () {
                  Navigator.pop(context);
                  if (widget.onConfirm != null) {
                    List tempMapList = [];
                    List tempNameList = [];
                    List tempIdList = [];
                    selectDataMake(
                        dataList, tempMapList, tempIdList, tempNameList);
                    widget.onConfirm!(tempMapList, tempIdList, tempNameList,
                        jsonEncode(dataList));
                  }
                },
                child: Container(
                  padding: EdgeInsets.only(right: 10.w),
                  color: Colors.white,
                  child: Text(
                    '确定',
                    style: TextStyle(color: Colors.blue, fontSize: 14.w),
                  ),
                ),
              ),
            ],
          ),
        ),
        Container(
          color: Colors.white,
          child: Container(
            margin: EdgeInsets.symmetric(horizontal: 10.w, vertical: 10.w),
            decoration: BoxDecoration(
              color: const Color(0xffF5F6F7),
              borderRadius: BorderRadius.circular(100.w),
            ),
            child: TextField(
              maxLines: 1,
              controller: controller,
              textAlignVertical: TextAlignVertical.center,
              decoration: InputDecoration(
                isDense: true,
                fillColor: const Color(0xffF5F6F7),
                border: InputBorder.none,
                constraints: BoxConstraints(maxHeight: 36.w),
                contentPadding:
                    EdgeInsets.only(left: 0, top: 0, bottom: 0, right: 15.w),
                prefixIcon:
                    const Icon(Icons.search_rounded, color: Color(0x991d2541)),
                hintText: "请输入搜索内容",
                hintStyle: TextStyle(
                  color: const Color(0x991d2541),
                  fontSize: 14.sp,
                ),
              ),
              cursorColor: const Color(0xff1D2541),
              style: TextStyle(
                fontSize: 14.sp,
                color: const Color(0xff1D2541),
              ),
              onChanged: (value) {
                Future.delayed(const Duration(milliseconds: 500), () {
                  searchMake(dataList, value);
                  setState(() {});
                });
              },
            ),
          ),
        ),
        Container(
          color: Colors.white,
          padding: EdgeInsets.only(top: 10.w, left: 5.w),
          height: 520.w,
          child: MediaQuery.removePadding(
            context: context,
            removeTop: true,
            child: ListView(
                shrinkWrap: true,
                children: List.generate(
                    dataList.length,
                    (index) => TreeSelectMultipleItemView(
                        childrenKey: widget.childrenKey,
                        idKey: widget.idKey,
                        valueKey: widget.valueKey,
                        level: 0,
                        expand: widget.expand,
                        initSelectList: initSelectList,
                        itemData: dataList[index]))),
          ),
        ),
      ],
    );
  }
}

class TreeSelectMultipleItemView extends StatefulWidget {
  // 子集Key
  final String childrenKey;
  // idKey
  final String idKey;
  // valueKey
  final String valueKey;
  // 层级
  final int level;
  // 当前层数据
  final Map itemData;
  // 上层处理回调
  final Function? parentCheck;
  // 是否默认展开;
  final bool expand;
  // 初始化选中
  final List<String> initSelectList;

  const TreeSelectMultipleItemView({
    required this.childrenKey,
    required this.idKey,
    required this.valueKey,
    required this.level,
    required this.itemData,
    required this.expand,
    this.parentCheck,
    this.initSelectList = const [],
    Key? key,
  }) : super(key: key);

  @override
  _TreeSelectMultipleItemViewState createState() =>
      _TreeSelectMultipleItemViewState();
}

class _TreeSelectMultipleItemViewState
    extends State<TreeSelectMultipleItemView> {
  @override
  void initState() {
    super.initState();
    if (widget.itemData['expand'] == null) {
      if (widget.itemData[widget.childrenKey] != null &&
          widget.itemData[widget.childrenKey].length != 0) {
        widget.itemData['expand'] = widget.expand;
      } else {
        widget.itemData['expand'] = widget.expand;
      }
    }
    if (widget.itemData['show'] == null) {
      widget.itemData['show'] = true;
    }
    if (widget.itemData['check'] == null) {
      widget.itemData['check'] = 0;
      if (widget.itemData[widget.childrenKey] == null ||
          widget.itemData[widget.childrenKey].isEmpty) {
        if (widget.initSelectList.contains(widget.itemData[widget.valueKey])) {
          widget.itemData['check'] = 2;
          //延时执行
          Future.delayed(const Duration(milliseconds: 100), () async {
            // 上层处理
            if (widget.parentCheck != null) {
              widget.parentCheck!();
            }
          });
        }
      }
    }
    setState(() {});
  }

  iconClick(Map itemData) {
    if (itemData[widget.childrenKey] != null &&
        itemData[widget.childrenKey].length != 0) {
      itemData['expand'] = !itemData['expand'];
    } else {
      itemData['check'] = itemData['check'] == 0 ? 2 : 0;
    }
    setState(() {});
  }

  itemClick(Map itemData) {
    itemData['check'] = itemData['check'] == 0 ? 2 : 0;
    if (itemData[widget.childrenKey] != null &&
        itemData[widget.childrenKey].length != 0) {
      // 下层处理
      String localItemJson = jsonEncode(itemData);
      localItemJson = localItemJson
          .replaceAll('"check":0', '"check":${itemData["check"]}')
          .replaceAll('"check":1', '"check":${itemData["check"]}')
          .replaceAll('"check":2', '"check":${itemData["check"]}');
      itemData.addAll(jsonDecode(localItemJson));
    }
    setState(() {});
    // 上层处理
    if (widget.parentCheck != null) {
      widget.parentCheck!();
    }
  }

  makeParentCheck() {
    int checkCount0 = 0;
    int checkCount2 = 0;
    for (Map item in widget.itemData[widget.childrenKey] ?? []) {
      if (item['check'] == 0) {
        checkCount0++;
      } else if (item['check'] == 2) {
        checkCount2++;
      }
    }

    if (checkCount0 == (widget.itemData[widget.childrenKey] ?? []).length) {
      widget.itemData['check'] = 0;
    } else if (checkCount2 ==
        (widget.itemData[widget.childrenKey] ?? []).length) {
      widget.itemData['check'] = 2;
    } else {
      widget.itemData['check'] = 1;
    }
    if (widget.parentCheck != null) {
      widget.parentCheck!();
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    IconData selectIcon = Icons.check_box;
    if (widget.itemData['check'] == 2) {
      selectIcon = Icons.check_circle;
    } else if (widget.itemData['check'] == 1) {
      selectIcon = Icons.remove_circle;
    } else {
      selectIcon = Icons.circle_outlined;
    }
    return widget.itemData['show']
        ? Container(
            padding: EdgeInsets.only(top: 8.w),
            child: Column(
              children: [
                InkWell(
                  onTap: () => itemClick(widget.itemData),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      InkWell(
                        onTap: (widget.itemData[widget.childrenKey] != null &&
                                widget.itemData[widget.childrenKey].isNotEmpty)
                            ? () => iconClick(widget.itemData)
                            : null,
                        child: Container(
                          padding: EdgeInsets.only(
                            left: widget.level * 26.w,
                          ),
                          child: (widget.itemData[widget.childrenKey] != null &&
                                  widget
                                      .itemData[widget.childrenKey].isNotEmpty)
                              ? Icon(
                                  widget.itemData['expand']
                                      ? Icons.keyboard_arrow_down
                                      : Icons.keyboard_arrow_right,
                                  color: const Color(0x991d2541),
                                  size: 22.w,
                                )
                              : SizedBox(
                                  width: 22.w,
                                ),
                        ),
                      ),
                      SizedBox(width: 8.w),
                      Icon(selectIcon, color: const Color(0x991d2541)),
                      SizedBox(width: 8.w),
                      Text(
                        '${widget.itemData[widget.valueKey] ?? ''}',
                        textAlign: TextAlign.center,
                        style: TextStyle(color: Colors.black, fontSize: 14.w),
                      ),
                    ],
                  ),
                ),
                widget.itemData['expand']
                    ? Column(
                        children: List.generate(
                            (widget.itemData[widget.childrenKey] ?? []).length,
                            (index) => TreeSelectMultipleItemView(
                                childrenKey: widget.childrenKey,
                                idKey: widget.idKey,
                                valueKey: widget.valueKey,
                                level: widget.level + 1,
                                itemData: widget.itemData[widget.childrenKey]
                                    [index],
                                expand: widget.expand,
                                initSelectList: widget.initSelectList,
                                parentCheck: makeParentCheck)))
                    : Container(),
              ],
            ),
          )
        : Container();
  }
}
